#-*- coding: utf-8 -*-
'''
Created on Sep 5, 2012

@author: bbg
'''
from common.debug import Debug
from helper.login_session_manager import LoginSessionManager
import dbwrapper,json
from helper.cdkey_manager import CdkeyManager
from dbwrapper.db_instance import DB_Instance


class ServiceBase(object):
    
    _dbsession_ = None
    
    def __init__(self, start_response):
        self._start_response = start_response
        self.debug = Debug()
        
        if ServiceBase._dbsession_  == None  or ServiceBase._dbsession_ is None:
            self.db_instance=DB_Instance()
            ServiceBase._dbsession_=self.db_instance.session()
            
        self.company_id = None
        self.shop_id = None            
        
    def _response(self, output):
        if ServiceBase._dbsession_ != None:    
            ServiceBase._dbsession_.close()    
            ServiceBase._dbsession_ = None
       
            
        status = '200 ok'
    
        #response_headers = [('Content-type', 'application/x-protobuf'),
        response_headers = [('Content-type', 'text/plain'),
                    ('Content-Length', str(len(output)))]
        
        self.debug.d("ServiceBase _response output:%s" % output)
        self._start_response(status, response_headers)
        
        return [output]


    def _responsefiles(self, output):
        if ServiceBase._dbsession_ != None:    
            ServiceBase._dbsession_.close()  
            ServiceBase._dbsession_ = None  
       
            
        status = '200 ok'
    
        #response_headers = [('Content-type', 'application/x-protobuf'),
        response_headers = [('Content-type', 'application/octet-stream'),
                    ('Content-Length', str(len(output)))]
           
        self._start_response(status, response_headers)
        
        return [output]
    
    def _responseInvalidParam(self):

        if ServiceBase._dbsession_ != None:
            ServiceBase._dbsession_.close()
            ServiceBase._dbsession_ = None

        response_params={}
        response_params['ret'] =-1
        response_params['msg'] = 'invalid parameter'
        response_params['data']=''
        strtemp=json.dumps(response_params)
 
        return self._response(strtemp)
    
    
        
    def _responseError(self, code, msg):

        if ServiceBase._dbsession_ != None:                         
            ServiceBase._dbsession_.close() 
            ServiceBase._dbsession_ = None

        response_params={}
        response_params['ret'] =code
        response_params['msg'] = msg
        response_params['data']='sorry'
        strtemp = json.dumps(response_params)
                        
        return self._response(strtemp)    
    
    
    def _returndbsession(self):
        if ServiceBase._dbsession_  == None  or ServiceBase._dbsession_ is None:
            self.db_instance = DB_Instance()
            ServiceBase._dbsession_ = self.db_instance.session()

        #conn = ServiceBase._dbsession_.connection()
        #if conn is not None:
        #    conn.connect()                
        return ServiceBase._dbsession_     
    
    
    
    def _isWebLogin(self, params):
        if params.has_key('company_id') == False:
            self.debug.e("ServiceBase._isWebLogin no company_id parameter")
            return False
        if params.has_key('username') == False or params.has_key('token') == False:
            self.debug.e("ServiceBase._isWebLogin no username or token parameter")
            return False
        
        company_id = params.getfirst('company_id')
        username = params.getfirst('username')
        token = params.getfirst('token')
        
        return LoginSessionManager.isValidSession(company_id, username, token, self._returndbsession())
    
    def _isClientLogin(self, params):
        '''
            check client login
            1. cdkey validation
            2. session validation
        '''
        if params.has_key('cdkey') == False or params.has_key('uuid') == False:
            self.debug.e("ServiceBase._isClientLogin no cdkey or uuid parameter")
            return False
        if params.has_key('username') == False or params.has_key('token') == False:
            self.debug.e("ServiceBase._isClientLogin no username or token parameter")
            return False
        
        if hasattr(params, 'getfirst'):
            cdkey = params.getfirst('cdkey')
            uuid = params.getfirst('uuid')        
            username = params.getfirst('username')
            token = params.getfirst('token')
        else:
            cdkey = params['cdkey']
            uuid = params['uuid']
            username = params['username']
            token = params['token'] 
                
        #check cdkey mapping
        dbmap = CdkeyManager.getCompanyShopIdPair(cdkey, self._returndbsession())
        if dbmap == None:
            self.debug.e("ServiceBase._isClientLogin cdkey no corresponding company or shop id:%s" % cdkey)
            return False
        
        if CdkeyManager.isValide(cdkey, uuid, self._returndbsession()) is False:
            #response cdkey invalid, login failed
            self.debug.e('ServiceBase._isClientLogin invalid %s' % cdkey)
            return False
        
        company_id = dbmap[0]
        shop_id = dbmap[1]

        self.company_id = company_id
        self.shop_id = shop_id
                        
        return LoginSessionManager.isValidSession(company_id, username, token, self._returndbsession())
    
    def _getCompanyShopId(self):
        '''
            get companyid and shopid after client login
        '''
        return (self.company_id, self.shop_id)
    